package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.admin.model.TbUser;
import com.dongdongshop.admin.vo.AddressVO;
import com.dongdongshop.common.Result;
import com.dongdongshop.service.AddressService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping
    public Result getAddress(@RequestHeader String AutharizeToken){
        Claims claims = JwtUtil.parseJwt(AutharizeToken);
        LoginUser tbUser= JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        List<AddressVO> addressVOList = addressService.getByUserId(tbUser.getUname());
        return Result.OK().setData(addressVOList);
    }

    @PostMapping("add")
    public Result add(@RequestBody AddressVO addressVO,@RequestHeader String AutharizeToken){
        Claims claims = JwtUtil.parseJwt(AutharizeToken);
        LoginUser tbUser= JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        addressService.add(addressVO,tbUser);
        return Result.OK();
    }

    @PostMapping("getAll")
    public Result getAll(){
        List<AddressVO> addressVOList = addressService.getAll();
        return Result.OK().setData(addressVOList);
    }

    @PostMapping("getId")
    public Result getAddrById(@RequestParam Long id){
       AddressVO vo =  addressService.getAddrById(id);
        return Result.OK().setData(vo);
    }
}
